package codingforgreat.lchot150;

import java.util.*;

public class Lc227 {

    public int calculate(String s) {
        LinkedList<String> queue = new LinkedList<>();
        char[] str = s.replace(" ","").toCharArray();
        int p1 = 0;
        int p2 = 0;
        for(int i = 0;i < str.length;i++){
            if(str[i] == '+' || str[i] == '-'){
                queue.add(String.valueOf(p1));
                p1 = 0;
                queue.add(String.valueOf(str[i]));
            }else if(str[i] == '*' || str[i] == '/'){
                char ss = str[i];
                i++;
                while(i < str.length &&(str[i] != '+' && str[i] != '-' && str[i] != '*' && str[i] != '/')){
                    p2 = (p2 * 10) + str[i++] - '0';
                }
                i--;
                switch(ss){
                    case '*':
                        p1 = p1 * p2;
                        p2 = 0;
                        if(i == str.length - 1){
                            queue.add(String.valueOf(p1));
                        }
//                        queue.add(String.valueOf(p1));
//                        p1 = 0;
                        break;
                    case'/':
                        p1 = p1 / p2;
                        p2 = 0;
                        if(i == str.length - 1){
                            queue.add(String.valueOf(p1));
                        }
//                        queue.add(String.valueOf(p1));
//                        p1 = 0;
                        break;
                }
            }else{
                p1 = (p1 * 10) + str[i] - '0';
                if(i == str.length - 1){
                    queue.add(String.valueOf(p1));
                }
            }

        }
        int a  = 0;
        int b = 0;
        s = null;
        int res = 0;
        if(queue.isEmpty()){
            return p1;
        };
        while(queue.size() != 1){
            a = Integer.valueOf(queue.poll());
            s = queue.poll();
            b =  Integer.valueOf(queue.poll());
            switch(s){
                case"+":
                    res = a + b;
                    queue.addFirst(String.valueOf(res));
                    break;
                case"-":
                    res = a - b ;
                    queue.addFirst(String.valueOf(res));
                    break;
            }
        }

        return Integer.valueOf(queue.poll());

    }

    public static void main(String[] args) {
        Lc227 lc = new Lc227();
        System.out.println(lc.calculate("2*3+4"));
    }
}
